import { 
  renderImperatively,
  type ImperativeHandler,
} from '../../utils/render-imperatively'
import { InternalToast } from './toast'
import type {
  ToastConfigProps,
  ToastShowProps,
  ToastHandler,
} from './type'

let currentTimeout: number | null = null
let currentHandler: ImperativeHandler | null = null

/* ======================================= logic =============================================== */
const defaultProps: ToastShowProps = {
  duration: 2000,
  position: 'center',
  maskClickable: false,
}

export const config = (val: ToastConfigProps): void => {
  if (val.duration !== undefined) {
    defaultProps.duration = val.duration
  }
  if (val.position !== undefined) {
    defaultProps.position = val.position
  }
  if (val.maskClickable !== undefined) {
    defaultProps.maskClickable = val.maskClickable
  }
}

export const clear = (): void => {
  currentHandler?.close()
  currentHandler = null
}

// 绕过props ts 检查
const ToastInner = (
  props: ToastShowProps & {
    onClose?: () => void
  },
) => (<InternalToast {...props} />)

export const show = (p: ToastShowProps | string): ToastHandler => {
  let props = { ...defaultProps }

  if (typeof p === 'string') {
    props = {
      ...props,
      content: p,
    }
  }

  if (typeof p === 'object') {
    props = {
      ...props,
      ...p,
    }
  }

  const element = (
    <ToastInner
      {...props}
      onClose={() => {
        currentHandler = null // 手动调用`currentHandler.close()` 时 重置 `currentHandler`
      }}
    />
  )

  if (currentHandler) {
    currentHandler.replace(element)
  } else {
    currentHandler = renderImperatively(element)
  }

  if (currentTimeout) {
    window.clearTimeout(currentTimeout)
    currentTimeout = null
  }

  if (props.duration !== 0) {
    currentTimeout = window.setTimeout(() => {
      clear()
    }, props.duration)
  }

  return currentHandler
}
